//
//  JWFindBussinessReleaseExitVC.m
//  jinwang
//
//  Created by jzb on 2018/4/12.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "JWFindBussinessReleaseExitVC.h"

@interface JWFindBussinessReleaseExitVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextView *FaBuTextView;
@property (nonatomic,strong) NSMutableString *resultString;//拼接之后的字符串
@property (nonatomic,strong)NSMutableArray *imageUploadedArray;//图片数组
@property (nonatomic,strong)NSMutableArray *imageUploadedNameArray;//所有上传图片名字数组（上传图片之后，返回的名字）
@property (nonatomic,strong)NSMutableArray *imageDownloadedNameArray;//之前上传的oldHtmlString解析出来的图片地址

@property (nonatomic,strong)NSMutableArray *imageMarkArray;//图片对应的记号`0`表示第0张图片

@property (nonatomic,strong)UIImagePickerController *pickerController;
@property (nonatomic,assign)CGFloat imageWidth;
@property (nonatomic,assign)CGFloat wordFont;

//光标位置
@property (nonatomic,assign)NSRange curserRange;

@end

@implementation JWFindBussinessReleaseExitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.f) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    _wordFont = 16.0;
    _imageWidth = 300;
    
    _resultString = [[NSMutableString alloc] init];
    _imageUploadedArray = [[NSMutableArray alloc] init];
    _imageUploadedNameArray = [[NSMutableArray alloc] init];
    _imageDownloadedNameArray = [[NSMutableArray alloc] init];
    
    _imageMarkArray = [[NSMutableArray alloc] init];
//    _FaBuTextView = [[UITextView alloc]initWithFrame:CGRectMake(20, 10, kScreenWidth-40, _JiaWenTextBGView.height-70)];
    _FaBuTextView.font = [UIFont systemFontOfSize:_wordFont];
//    _serviceContentTextView.delegate = self;
    _FaBuTextView.returnKeyType = UIReturnKeyDone;
//    [_serviceContentTextView setFont:[UIFont systemFontOfSize:16]];
//    [_JiaWenTextBGView addSubview:_serviceContentTextView];
    //    if (_oldHtmlString != nil && ![_oldHtmlString isEqualToString:@""]) {
    //        [self setOldStringToAttributeString:_oldHtmlString];
    //    }
    
    if (_ExitAttributedString.length > 0) {
        
        _FaBuTextView.attributedText = _ExitAttributedString;
    }
    
    if (_pickerController == nil) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            _pickerController = [[UIImagePickerController alloc] init];
            _pickerController.view.backgroundColor = [UIColor redColor];
            _pickerController.delegate = self;
            _pickerController.allowsEditing = NO;
        });
    }
}
- (IBAction)AddImgBtnOnclick:(UIButton *)sender {
    
    UIAlertController*ZhengC=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction*XiangCe=[UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:_pickerController animated:YES completion:nil];
    }];
    UIAlertAction*ZhaoXiang=[UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_pickerController animated:YES completion:nil];
        
    }];
    UIAlertAction*  Cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    
    [ZhengC addAction:XiangCe];
    [ZhengC addAction:ZhaoXiang];
    [ZhengC addAction:Cancel];
    [self presentViewController:ZhengC animated:YES completion:nil];
    
}
- (IBAction)OKBtnOnclick:(UIButton *)sender {
    
    if (_FaBuTextView.attributedText.length > 0) {
        self.ExitBlcok(_FaBuTextView.attributedText);
        [self goBack];
    }else{
        
        [self showBottomMessag:@"请输入内容"];
    }
    
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"选择了一张图片");
    UIImage *userImage = info[UIImagePickerControllerOriginalImage];
    [_pickerController dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithAttributedString:_FaBuTextView.attributedText];
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [self imageCompressForWidth:userImage targetWidth:_FaBuTextView.width];
    // 设置图片大小
    //        attch.bounds = CGRectMake(40, 0, kScreenWidth-60, kScreenWidth-60);
    
    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri replaceCharactersInRange:_curserRange withAttributedString:string];
    
    // 用label的attributedText属性来使用富文本
    _FaBuTextView.attributedText = attri;
    [_FaBuTextView setFont:[UIFont systemFontOfSize:_wordFont]];
    
}
//图文混排
- (void)textViewDidChangeSelection:(UITextView *)textView {
    NSLog(@"光标位置%ld——%ld",textView.selectedRange.location,textView.selectedRange.length);
    _curserRange = textView.selectedRange;
}
#pragma mark ------------图片处理------------------
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
//    UIGraphicsBeginImageContext(size);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
